package dyyx.util;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;

public class MetricItem {
	
	private String name = null;
	private TreeMap<String,String> labels;
	
	
	private Number value;
	
	
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public TreeMap<String, String> getLabels() {
		return labels;
	}
	public void setLabels(TreeMap<String, String> labels) {
		this.labels = labels;
	}
	public Number getValue() {
		return value;
	}
	public void setValue(Number value) {
		this.value = value;
	}
	
	
	public static MetricItem build(String name,Number value){
		if(StringUtils.isBlank(name)){
			return null;
		}
		name = name.trim();
		if(value==null){
			return null;
		}
		MetricItem mi = new MetricItem();
		mi.name= name;
		mi.value = value;
		return mi;
	}
	
	public static MetricItem build(String name,Number value,String labelName,String labelValue){
		if(StringUtils.isBlank(name)){
			return null;
		}

		name = name.trim();
		if(value==null){
			return null;
		}
		
		if(StringUtils.isBlank(labelName)){
			return null;
		}
		if(StringUtils.isBlank(labelValue)){
			return null;
		}
		labelValue = labelValue.trim();
		labelName = labelName.trim();
		
		
		MetricItem mi = new MetricItem();
		mi.name= name;
		mi.value = value;
		
		TreeMap<String,String> labels = new TreeMap<String,String>();
		labels.put(labelName, labelValue);
		mi.setLabels(labels);
		
		return mi;
	}
	
	public static MetricItem build(String name,Number value,TreeMap<String,String> labels){
		if(StringUtils.isBlank(name)){
			return null;
		}
		
		name = name.trim();
		if(value==null){
			return null;
		}
		if(labels==null || labels.isEmpty()){
			return null;
		}
		
		MetricItem mi = new MetricItem();
		mi.name= name;
		mi.value = value;
		
		
		mi.setLabels(labels);
		
		return mi;
	}
	
	@Override
	public String toString(){
		StringBuilder sb = new StringBuilder();
		
		sb.append(name);
		
		if(labels!=null && !labels.isEmpty()){
			sb.append("{");
			Set<Map.Entry<String, String>> kvs = labels.entrySet();
			boolean first = true;
			for(Map.Entry item:kvs){
				
				if(first){
					first = false;
				}else{
					sb.append(",");
				}
				
				sb.append(item.getKey());
				sb.append("=").append("\"");
				sb.append(item.getValue());
				sb.append("\"");
				
			}
					
			sb.append("}");

		}
		
		sb.append(" ").append(value);

		return sb.toString();
	}
	
	

	
	
	
}
